
#include <QBoxLayout>
#include <QEvent>
#include <QPoint>
#include <QKeyEvent>
#include <QRect>
#include <QDesktopWidget>

#include "WPData.h"
#include "wpcommentlistitem.h"
#include "WPNetworkEngine.h"
#include "MDragWidget.h"

static const int KCommentDefaultHeight = 57;

WPCommentListItem::WPCommentListItem(MDragWidget& aParent, WPComment aComment, bool aShowFullComment)
    : QFrame(&aParent), iParent(aParent), iComment(aComment)
{
    ui.setupUi(this);

    iShowFullComment = aShowFullComment;

    ui.postTitle->setTextFormat(Qt::RichText);
    ui.url->setElideMode(Qt::ElideMiddle);
    ui.email->setElideMode(Qt::ElideMiddle);
    ui.timeStamp->setElideMode(Qt::ElideRight);
    
    Update(aComment);

    SetViewMode(iShowFullComment);
    setFrameStyle(QFrame::Box);
    setContextMenuPolicy(Qt::NoContextMenu);
}

WPCommentListItem::~WPCommentListItem()
{

}

void WPCommentListItem::SetAvatarImage(const QPixmap& aPixmap)
{
    if (!aPixmap.isNull())
        ui.avatar->setPixmap(aPixmap);
}

void WPCommentListItem::mouseReleaseEvent(QMouseEvent *e)
{
    if (hasFocus() && !iParent.MDragWidgetIsDragging())
    {
        emit CommentItemSelected(this);
    }
    QFrame::mouseReleaseEvent(e);
}

void WPCommentListItem::keyPressEvent(QKeyEvent *e)
{
    if (e->key() == Qt::Key_Select || e->key() == Qt::Key_Enter)
    {
        emit CommentItemSelected(this);
        e->accept();
    }
    else
    {
        QFrame::keyPressEvent(e);
    }
}

WPComment WPCommentListItem::GetComment() const
{
    return iComment;
}

QPoint WPCommentListItem::TopRight() const
{
    return geometry().topRight();
}

void WPCommentListItem::ChangeViewMode()
{
    iShowFullComment = !iShowFullComment;
    SetViewMode(iShowFullComment);
}

void WPCommentListItem::SetViewMode(bool aShowFullComment)
{
    if (aShowFullComment)
    {
        ui.commentText->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
        ui.commentText->setWordWrap(true);
        ui.commentText->setMaximumHeight(QWIDGETSIZE_MAX);
    }
    else
    {
        ui.commentText->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
        ui.commentText->setFixedHeight(KCommentDefaultHeight);
    }
}

void WPCommentListItem::Update (WPComment aComment)
{
    iComment = aComment;
    ui.postTitle->setText("to " + aComment->iPostTitle);
    ui.authorName->setText(aComment->iAuthor);
    ui.timeStamp->setText(aComment->GetShortLocalTimeString());
    ui.commentText->setText(aComment->iContent);

    if (!aComment->iAuthorUrl.isEmpty()) {
        ui.url->show();
        ui.url->setText(aComment->iAuthorUrl);

    } else {
        ui.url->hide();
    }

    ui.email->setText(aComment->iAuthorEmail);
}
